#!/usr/bin/env perl
use strict;

# This script will recombine the perltidy binary script and all of its
# modules into a single, monolithic script, which is how it was
# originally distributed.  It might be useful for users who have
# difficulty installing modules, or prefer not to.

# usage:
#   perl pm2pl

# Run this from the perltidy main installation directory.  It reads
# bin/perltidy and lib/*.pm and writes a file 'perltidy' in the
# current directory.

# Then, put the file 'perltidy' in your path and it should work (You
# will also need to put the batch file 'perltidy.bat' in your path
# under msdos/windows)

# For unix systems, a sample Makefile is included as Makefile.npm

# This should work for a system with File::Spec,
# and for older Windows/Unix systems without File::Spec.
my $script = 'bin/perltidy';
my $module = 'lib/Perl/Tidy.pm';
eval "use File::Spec;";
my $missing_file_spec = $@;
unless ($missing_file_spec) {
    $script = File::Spec->catfile( 'bin', 'perltidy' );
    $module = File::Spec->catfile( 'lib', 'Perl', 'Tidy.pm' );
}

my $outfile = "perltidy";
open OUTFILE, "> $outfile" or die "can't open file '$outfile' : $!\n";
print "Creating file '$outfile' ....\n ";

# first, open the script and copy the first (hash-bang) line
# (Note: forward slashes in file names here will work in Windows)
open SCRIPT, "< $script" or die "can't open script file '$script' : $!\n";
my $hash_bang = <SCRIPT>;
print OUTFILE $hash_bang;

# then copy all modules (only one for now)
open PM, "< $module" or die "can't open my module file '$module' : $!\n";
while (<PM>) {
    last if /^\s*__END__\s*$/;
    print OUTFILE;
}
close PM;

# then, copy the rest of the script except for the 'use PerlTidy' statement
while (<SCRIPT>) {
    last if /^\s*__END__\s*$/;
    print OUTFILE unless $_ =~ /use Perl::Tidy/;
}
close SCRIPT;
close OUTPUT;
chmod 0755, $outfile;
print "...Done...\n";

my $testfile = "Makefile.PL";
if ( -e $testfile ) {
    print <<EOM;

You can now run perltidy. 
For a quick test, try reformatting $testfile with the following command:

    perl perltidy -lp $testfile

and then compare the output in $testfile.tdy with the original file
EOM
}
else {
    $testfile = "somefile";
    print <<EOM;

You can now run perltidy to reformat any perl script.  
For example, the following command:

    perl perltidy $testfile

will produce the output file $testfile.tdy
EOM
}
